﻿using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

namespace WebPic.Sample.Comum {
    public class Repository<T> : IRepository<T>
    {
        private readonly DbContext _context;

        private DbSet<T> _set;
        public DbSet<T> Set {
            get { return _set ?? (_set = _context.Set<T>()); }
        }

        public Repository(DbContext context) {
            _context = context;
        }

        public void Add(T entity) {
            entity.DataCadastro = DateTime.Now;
            _set.Add(entity);
        }

        public void Update(T entity) {
            _context.Entry(entity).State = EntityState.Modified;
        }

        public void Remove(T entity) {
            _set.Remove(entity);
        }

        public IQueryable<T> Get(Expression<Func<T, bool>> predicate = null) {
            return predicate != null ? _set.Where(predicate) : _set;
        }

        public IQueryable<T> Get(ISpecification<T> criteria) {
            return _set.Where(criteria.Predicate);
        }

        public T Find(ISpecification<T> criteria) {
            return Set.FirstOrDefault(criteria.Predicate);
        }

        public T Find(params object[] keysValues) {
            return _set.Find(keysValues);
        }
    }
}